package com.android.clinic.doctors.app.base;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.android.clinic.doctors.app.R;
import com.android.clinic.doctors.app.adapter.BaseListAdapter;
import com.aspsine.swipetoloadlayout.OnLoadMoreListener;
import com.aspsine.swipetoloadlayout.OnRefreshListener;
import com.aspsine.swipetoloadlayout.SwipeToLoadLayout;

/**
 * Created by cheng on 2018/6/13.
 */
public abstract class BaseListActivity<T> extends BaseActivity implements OnRefreshListener, OnLoadMoreListener {

    protected SwipeToLoadLayout swipeToLoadLayout;
    protected BaseListAdapter<T> mAdapter;
    protected int pageSize = 10;  // 每页请求数量
    protected int pageNum = 1; // 当前页数

    @Override
    protected int getLayoutResId() {
        return getLayoutResId();
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        swipeToLoadLayout = findViewById(R.id.swipeToLoadLayout);
        RecyclerView recyclerView = findViewById(R.id.swipe_target);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(linearLayoutManager);

        swipeToLoadLayout.post(() -> swipeToLoadLayout.setRefreshing(true));
        swipeToLoadLayout.setOnRefreshListener(this);
        swipeToLoadLayout.setOnLoadMoreListener(this);
        mAdapter = getAdapter();
        recyclerView.setAdapter(mAdapter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        refreshComplete();
    }

    protected void refreshComplete() {
        if (null != swipeToLoadLayout) {
            if (swipeToLoadLayout.isRefreshing()) {
                swipeToLoadLayout.setRefreshing(false);
                mAdapter.clear();
            }
            if (swipeToLoadLayout.isLoadingMore()) {
                swipeToLoadLayout.setLoadingMore(false);
            }
        }
    }

    @Override
    public void onLoadMore() {
        pageNum++;
        new Handler().postDelayed(this::reloadData, 300);

    }

    @Override
    public void onRefresh() {
        pageNum = 1;
        new Handler().postDelayed(this::reloadData, 300);
    }

    protected abstract void reloadData();


    protected abstract BaseListAdapter<T> getAdapter();
}
